using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Domain.Repositories;
using AdminSG3L.Applicaticn.ServicesInterface;
using AdminSG3L.Applicaticn.Commands;
using Serilog;
using AdminSG3L.Applicaticn.Dtos;

namespace AdminSG3L.Applicaticn.Services;

public class PermissionService(IRepository<AppPermission> permissionRepository) : IPermissionService
{
    private readonly IRepository<AppPermission> _permissionRepository = permissionRepository;

    public async Task<ApiResponse<AppPermission?>> GetByIdAsync(Guid id)
    {
        if (id == Guid.Empty)
        {
            return ApiResponse<AppPermission?>.Fail("权限ID无效");
        }
        try
        {
            var permission = await _permissionRepository.GetByIdAsync(id);
            if (permission == null)
            {
                return ApiResponse<AppPermission?>.Fail("权限不存在");
            }
            else
            {
                return ApiResponse<AppPermission?>.Success(permission);
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex, "获取权限异常，Id={PermissionId}", id);
            return ApiResponse<AppPermission?>.Fail($"获取权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<PermissionDto>> CreateAsync(CreatePermissionDto dto)
    {
        var permission = AppPermission.Create(dto.PermissionName, dto.PermissionCode, dto.Description, dto.ParentId);
        permission.IsActive = dto.IsActive; // 设置激活状态
        await _permissionRepository.AddAsync(permission);
        var result = new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt);
        return ApiResponse<PermissionDto>.Success(result);
    }

    public async Task<ApiResponse<IEnumerable<PermissionDto>>> BatchCreateAsync(IEnumerable<CreatePermissionDto> dtos)
    {
        var permissions = dtos.Select(dto => AppPermission.Create(dto.PermissionName, dto.PermissionCode, dto.Description)).ToList();
        await _permissionRepository.AddRangeAsync(permissions);
        var result = permissions.Select(permission => new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt));
        return ApiResponse<IEnumerable<PermissionDto>>.Success(result);
    }

    public async Task<ApiResponse<bool>> UpdateAsync(UpdatePermissionDto dto)
    {
        var permission = await _permissionRepository.GetByIdAsync(dto.Id);
        if (permission == null)
            return ApiResponse<bool>.Fail("权限不存在");
        permission.Update(dto.PermissionName, dto.PermissionCode, dto.Description, dto.ParentId, dto.IsActive);
        await _permissionRepository.UpdateAsync(permission);
        return ApiResponse<bool>.Success(true);
    }

    public async Task<ApiResponse<bool>> DeleteAsync(Guid id)
    {
        if (id == Guid.Empty)
        {
            return ApiResponse<bool>.Fail("权限ID无效");
        }
        try
        {
            var permission = await _permissionRepository.GetByIdAsync(id);
            if (permission == null)
            {
                return ApiResponse<bool>.Fail("权限不存在");
            }

            // 检查是否已经被软删除
            if (permission.IsDeleted)
            {
                return ApiResponse<bool>.Fail("权限已被删除");
            }

            var allPermissions = await _permissionRepository.GetAllAsync();
            var deletedCount = 0;

            // 递归收集所有子权限并执行软删除
            var permissionsToDelete = new List<AppPermission>();
            CollectChildPermissions(permission, allPermissions, permissionsToDelete);

            // 执行软删除
            foreach (var permissionToDelete in permissionsToDelete)
            {
                if (!permissionToDelete.IsDeleted)
                {
                    permissionToDelete.Delete(); // 调用EntityBase的Delete方法
                    permissionToDelete.UpdateTime(); // 更新时间戳
                    await _permissionRepository.UpdateAsync(permissionToDelete);
                    deletedCount++;
                }
            }
            
            Log.Information("权限级联软删除成功，根权限Id={PermissionId}, 删除总数={Count}", id, deletedCount);
            return ApiResponse<bool>.Success(true, $"删除成功，共删除 {deletedCount} 个权限");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "删除权限异常，Id={PermissionId}", id);
            return ApiResponse<bool>.Fail($"删除权限异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 级联删除权限（包括子权限）
    /// </summary>
    /// <param name="id">权限ID</param>
    /// <returns>删除结果</returns>
    public async Task<ApiResponse<int>> DeleteCascadeAsync(Guid id)
    {
        if (id == Guid.Empty)
        {
            return ApiResponse<int>.Fail("权限ID无效");
        }
        try
        {
            var permission = await _permissionRepository.GetByIdAsync(id);
            if (permission == null)
            {
                return ApiResponse<int>.Fail("权限不存在");
            }

            // 检查是否已经被软删除
            if (permission.IsDeleted)
            {
                return ApiResponse<int>.Fail("权限已被删除");
            }

            var allPermissions = await _permissionRepository.GetAllAsync();
            var deletedCount = 0;

            // 递归收集所有子权限
            var permissionsToDelete = new List<AppPermission>();
            CollectChildPermissions(permission, allPermissions, permissionsToDelete);

            // 执行软删除
            foreach (var permissionToDelete in permissionsToDelete)
            {
                if (!permissionToDelete.IsDeleted)
                {
                    permissionToDelete.Delete();
                    permissionToDelete.UpdateTime();
                    await _permissionRepository.UpdateAsync(permissionToDelete);
                    deletedCount++;
                }
            }

            Log.Information("级联删除权限成功，根权限Id={PermissionId}, 删除总数={Count}", id, deletedCount);
            return ApiResponse<int>.Success(deletedCount, $"级联删除成功，共删除 {deletedCount} 个权限");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "级联删除权限异常，Id={PermissionId}", id);
            return ApiResponse<int>.Fail($"级联删除权限异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 递归收集所有子权限
    /// </summary>
    /// <param name="permission">当前权限</param>
    /// <param name="allPermissions">所有权限列表</param>
    /// <param name="result">收集结果</param>
    private void CollectChildPermissions(AppPermission permission, IEnumerable<AppPermission> allPermissions, List<AppPermission> result)
    {
        result.Add(permission);
        
        // 查找直接子权限
        var children = allPermissions.Where(p => p.ParentId == permission.Id && !p.IsDeleted).ToList();
        
        // 递归收集子权限的子权限
        foreach (var child in children)
        {
            CollectChildPermissions(child, allPermissions, result);
        }
    }

    public async Task<ApiResponse<int>> BatchDeleteAsync(IEnumerable<Guid> ids)
    {
        if (ids == null || !ids.Any())
        {
            return ApiResponse<int>.Fail("ID集合不能为空");
        }
        try
        {
            var allPermissions = await _permissionRepository.GetAllAsync();
            var rootPermissions = allPermissions.Where(p => ids.Contains(p.Id) && !p.IsDeleted).ToList();
            
            if (!rootPermissions.Any())
            {
                return ApiResponse<int>.Fail("未找到要删除的权限或权限已被删除");
            }

            var allPermissionsToDelete = new List<AppPermission>();
            
            // 为每个根权限收集其所有子权限
            foreach (var rootPermission in rootPermissions)
            {
                var permissionsToDelete = new List<AppPermission>();
                CollectChildPermissions(rootPermission, allPermissions, permissionsToDelete);
                allPermissionsToDelete.AddRange(permissionsToDelete);
            }

            // 去重（避免重复删除同一权限）
            var uniquePermissionsToDelete = allPermissionsToDelete.Distinct().ToList();

            // 执行软删除
            int deletedCount = 0;
            foreach (var permission in uniquePermissionsToDelete)
            {
                if (!permission.IsDeleted)
                {
                    permission.Delete(); // 调用EntityBase的Delete方法
                    permission.UpdateTime(); // 更新时间戳
                    await _permissionRepository.UpdateAsync(permission);
                    deletedCount++;
                }
            }
            
            Log.Information("批量级联软删除权限成功，删除数量={Count}", deletedCount);
            return ApiResponse<int>.Success(deletedCount, $"批量删除成功，共删除 {deletedCount} 个权限");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "批量删除权限异常");
            return ApiResponse<int>.Fail($"批量删除权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetAllDtoAsync()
    {
        var permissions = await _permissionRepository.GetAllAsync();
        // 过滤掉已删除的权限
        var activePermissions = permissions.Where(p => !p.IsDeleted);
        var dtos = activePermissions.Select(permission => new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt));
        return ApiResponse<IEnumerable<PermissionDto>>.Success(dtos);
    }

    public async Task<ApiResponse<(IEnumerable<PermissionDto> Permissions, int TotalCount)>> GetPagedDtoAsync(int pageIndex, int pageSize)
    {
        try
        {
            var all = await _permissionRepository.GetAllAsync();
            // 过滤掉已删除的权限
            var activePermissions = all.Where(p => !p.IsDeleted);
            var total = activePermissions.Count();
            var page = activePermissions.Skip(pageIndex * pageSize).Take(pageSize)
                .Select(permission => new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt)).ToList();
            Log.Information($"权限分页查询: pageIndex={pageIndex}, pageSize={pageSize}, total={total}, returned={page.Count}");
            return ApiResponse<(IEnumerable<PermissionDto>, int)>.Success((page, total));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "分页获取权限异常");
            return ApiResponse<(IEnumerable<PermissionDto>, int)>.Fail($"分页获取权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<(IEnumerable<PermissionDto> Permissions, int TotalCount)>> GetPagedDtoAsync(int pageIndex, int pageSize, PermissionFilterDto? filter = null)
    {
        try
        {
            var all = await _permissionRepository.GetAllAsync();
            // 过滤掉已删除的权限
            var activePermissions = all.Where(p => !p.IsDeleted);
            
            // 应用筛选条件
            if (filter != null)
            {
                if (!string.IsNullOrWhiteSpace(filter.Name))
                {
                    activePermissions = activePermissions.Where(p => p.PermissionName.Contains(filter.Name, StringComparison.OrdinalIgnoreCase));
                }
                
                if (!string.IsNullOrWhiteSpace(filter.Code))
                {
                    activePermissions = activePermissions.Where(p => !string.IsNullOrEmpty(p.PermissionCode) && p.PermissionCode.Contains(filter.Code, StringComparison.OrdinalIgnoreCase));
                }
                
                if (filter.Status.HasValue)
                {
                    // 将int状态值转换为bool：1=true(启用), 0=false(禁用)
                    bool isActive = filter.Status.Value == 1;
                    activePermissions = activePermissions.Where(p => p.IsActive == isActive);
                }
                
                if (filter.ParentId.HasValue)
                {
                    activePermissions = activePermissions.Where(p => p.ParentId == filter.ParentId.Value);
                }
            }
            
            var total = activePermissions.Count();
            var page = activePermissions.Skip(pageIndex * pageSize).Take(pageSize)
                .Select(permission => new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt)).ToList();
            
            Log.Information($"权限筛选分页查询: pageIndex={pageIndex}, pageSize={pageSize}, filter={filter}, total={total}, returned={page.Count}");
            return ApiResponse<(IEnumerable<PermissionDto>, int)>.Success((page, total));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "筛选分页获取权限异常");
            return ApiResponse<(IEnumerable<PermissionDto>, int)>.Fail($"筛选分页获取权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<int>> GetCountAsync()
    {
        try
        {
            var all = await _permissionRepository.GetAllAsync();
            // 只统计未删除的权限
            var count = all.Count(p => !p.IsDeleted);
            return ApiResponse<int>.Success(count);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "获取权限总数异常");
            return ApiResponse<int>.Fail($"获取权限总数异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<PermissionDto?>> FindOneAsync(Func<PermissionDto, bool> predicate)
    {
        if (predicate == null)
        {
            return ApiResponse<PermissionDto?>.Fail("查询条件不能为空");
        }
        try
        {
            var permissions = await _permissionRepository.GetAllAsync();
            // 过滤掉已删除的权限
            var dtos = permissions.Where(p => !p.IsDeleted).Select(p => new PermissionDto(p.Id, p.PermissionName, p.PermissionCode, p.Description, p.IsActive, p.ParentId, p.CreatedAt, p.UpdatedAt));
            var result = dtos.FirstOrDefault(predicate);
            if (result == null)
            {
                return ApiResponse<PermissionDto?>.Fail("未找到权限");
            }
            else
            {
                return ApiResponse<PermissionDto?>.Success(result);
            }
        }
        catch (Exception ex)
        {
            Log.Error(ex, "条件查询单个权限异常");
            return ApiResponse<PermissionDto?>.Fail($"条件查询单个权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<IEnumerable<PermissionDto>>> FindManyAsync(Func<PermissionDto, bool> predicate)
    {
        if (predicate == null)
        {
            return ApiResponse<IEnumerable<PermissionDto>>.Fail("查询条件不能为空");
        }
        try
        {
            var permissions = await _permissionRepository.GetAllAsync();
            // 过滤掉已删除的权限
            var dtos = permissions.Where(p => !p.IsDeleted).Select(p => new PermissionDto(p.Id, p.PermissionName, p.PermissionCode, p.Description, p.IsActive, p.ParentId, p.CreatedAt, p.UpdatedAt));
            var result = dtos.Where(predicate);
            return ApiResponse<IEnumerable<PermissionDto>>.Success(result);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "条件查询多个权限异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"条件查询多个权限异常: {ex.Message}");
        }
    }

    public async Task<ApiResponse<PermissionDto?>> GetDtoByIdAsync(Guid id)
    {
        var permission = await _permissionRepository.GetByIdAsync(id);
        if (permission == null || permission.IsDeleted)
            return ApiResponse<PermissionDto?>.Fail("权限不存在");
        var dto = new PermissionDto(permission.Id, permission.PermissionName, permission.PermissionCode, permission.Description, permission.IsActive, permission.ParentId, permission.CreatedAt, permission.UpdatedAt);
        return ApiResponse<PermissionDto?>.Success(dto);
    }

    /// <summary>
    /// 为权限分配角色（权限-角色关联）
    /// </summary>
    /// <param name="permissionId">权限ID</param>
    /// <param name="roleId">角色ID</param>
    /// <returns>分配结果</returns>
    public async Task<ApiResponse<bool>> AssignRoleAsync(Guid permissionId, Guid roleId)
    {
        try
        {
            Log.Information("开始为权限分配角色，PermissionId={PermissionId}, RoleId={RoleId}", permissionId, roleId);
            
            // 检查权限是否存在
            var permission = await _permissionRepository.GetByIdAsync(permissionId);
            if (permission == null)
            {
                return ApiResponse<bool>.Fail("权限不存在");
            }

            // 注意：这里需要实现角色-权限关联表的逻辑
            Log.Warning("权限角色关联功能需要实现角色权限关联表");
            return ApiResponse<bool>.Success(true, "分配角色功能需要实现角色权限关联表");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "为权限分配角色异常");
            return ApiResponse<bool>.Fail($"为权限分配角色异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 移除权限的角色关联
    /// </summary>
    /// <param name="permissionId">权限ID</param>
    /// <param name="roleId">角色ID</param>
    /// <returns>移除结果</returns>
    public async Task<ApiResponse<bool>> RemoveRoleAsync(Guid permissionId, Guid roleId)
    {
        try
        {
            Log.Information("开始移除权限的角色关联，PermissionId={PermissionId}, RoleId={RoleId}", permissionId, roleId);
            
            var permission = await _permissionRepository.GetByIdAsync(permissionId);
            if (permission == null)
            {
                return ApiResponse<bool>.Fail("权限不存在");
            }

            Log.Warning("权限角色关联功能需要实现角色权限关联表");
            return ApiResponse<bool>.Success(true, "移除角色功能需要实现角色权限关联表");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "移除权限角色关联异常");
            return ApiResponse<bool>.Fail($"移除权限角色关联异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 设置权限启用状态
    /// </summary>
    /// <param name="permissionId">权限ID</param>
    /// <param name="enabled">是否启用</param>
    /// <returns>设置结果</returns>
    public async Task<ApiResponse<bool>> SetEnabledAsync(Guid permissionId, bool enabled)
    {
        try
        {
            Log.Information("开始设置权限启用状态，PermissionId={PermissionId}, Enabled={Enabled}", permissionId, enabled);
            
            var permission = await _permissionRepository.GetByIdAsync(permissionId);
            if (permission == null)
            {
                return ApiResponse<bool>.Fail("权限不存在");
            }

            // 检查Permission实体是否有IsActive属性
            Log.Information("权限启用状态设置功能需要确认Permission实体中的IsActive属性");
            return ApiResponse<bool>.Success(true, "设置启用状态功能需要确认Permission实体中的IsActive属性");
        }
        catch (Exception ex)
        {
            Log.Error(ex, "设置权限启用状态异常");
            return ApiResponse<bool>.Fail($"设置权限启用状态异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取顶级权限分组（用于筛选下拉框）
    /// </summary>
    /// <returns>顶级权限列表</returns>
    public async Task<ApiResponse<IEnumerable<PermissionDto>>> GetTopLevelPermissionsAsync()
    {
        try
        {
            var permissions = await _permissionRepository.GetAllAsync();
            var topLevelPermissions = permissions
                .Where(p => p.ParentId == null && !p.IsDeleted) // 过滤掉已删除的权限
                .Select(p => new PermissionDto(p.Id, p.PermissionName, p.PermissionCode, p.Description, p.IsActive, p.ParentId, p.CreatedAt, p.UpdatedAt))
                .ToList();
            
            Log.Information($"获取顶级权限分组: 总数={topLevelPermissions.Count}");
            return ApiResponse<IEnumerable<PermissionDto>>.Success(topLevelPermissions);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "获取顶级权限分组异常");
            return ApiResponse<IEnumerable<PermissionDto>>.Fail($"获取顶级权限分组异常: {ex.Message}");
        }
    }
} 